package network.impl;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.LinkedList;
import java.util.List;


class ConnectionThread extends Thread {
	private boolean running;
	private ServerSocket serverSocket;
	private int port;
	private List<ConnectionListener> listeners;
	
	ConnectionThread(int port) {
		this.port = port;
		serverSocket = null;
		listeners = new LinkedList<ConnectionListener>();
		running = true;
	}
	
	void addConnectionListener(ConnectionListener listener) {
		listeners.add(listener);
	}
	
	void shutDown()  {
		running = false;
	}
	
	@Override
	public void run() {
		try {
			serverSocket = new ServerSocket(port);
			
			serverSocket.setSoTimeout(3000);
			
			while (true) {
				
				try {
					Socket newSocket = serverSocket.accept();
					
					if (newSocket != null) {
						newConnection(new ServerThread(newSocket));
					}
				} catch (SocketTimeoutException ste) {
					if (!running) {
						break;
					}
				}				
			}
		
			serverSocket.close();
		} catch (IOException e) {
			// TODO add exception
		}
	}
	
	private void newConnection( ServerThread serverThread) {
		for(ConnectionListener listener : listeners) {
			listener.newConnection(serverThread);
		}
	}
}
